<template>
  <div>
    <el-drawer
      :title="title"
      :visible.sync="dialogFormVisible"
      size="800px"
      @close="close"
    >
      <el-form ref="form" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="班级" prop="classId">
          <el-select v-model="formData.classId" placeholder="请选择班级">
            <el-option
              v-for="item in classList"
              :key="item.id"
              :label="item.className"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-button @click="handleOpenEditor('classEditor')">
            新增班级
          </el-button>
        </el-form-item>
        <el-form-item label="教室" prop="classroomId">
          <el-select v-model="formData.classroomId" placeholder="请选择教室">
            <el-option
              v-for="item in classroomList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-button @click="handleOpenEditor('classroomEditor')">
            新增教室
          </el-button>
        </el-form-item>
        <el-form-item label="课程类型" prop="courseTypeId">
          <CourseTypeSelector v-model="formData.courseTypeId" />
        </el-form-item>
        <el-form-item label="选择教师" prop="teacherId">
          <el-select v-model="formData.teacherId" placeholder="请选择教师">
            <el-option
              v-for="item in teacherList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-button @click="handleOpenEditor('teacherEditor')">
            新增教师
          </el-button>
          <el-button @click="handleOpenTeacherFreeCalendar">
            查看教师时间
          </el-button>
        </el-form-item>
        <el-form-item label="学生" prop="studentIds">
          <el-checkbox-group v-model="formData.studentIds">
            <el-checkbox
              v-for="item in studentList"
              :key="item.id"
              :label="item.id"
            >
              {{ item.name }}
            </el-checkbox>
          </el-checkbox-group>
          <el-button @click="handleOpenEditor('studentEditor')">
            新增学生
          </el-button>
        </el-form-item>
        <el-form-item label="选择日期" prop="courseDate">
          <el-date-picker
            v-model="formData.courseDate"
            type="datetimerange"
            align="right"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['09:00:00', '22:00:00']"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button @click="close">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

    <ClassEditor ref="classEditor" @on-success="getClassList" />
    <ClassroomEditor ref="classroomEditor" @on-success="getClassroomList" />
    <TeacherEditor ref="teacherEditor" @on-success="getTeacherList" />
    <StudentEditor ref="studentEditor" @on-success="getStudentList" />
    <TeacherFreeCalendar ref="teacherFreeCalendarRef" />
  </div>
</template>

<script>
  import { format } from 'date-fns'
  import { createCourse, updateCourse } from '@/apis/course'
  import { getClassByPage } from '@/apis/class'
  import { getCourseTypeByPage } from '@/apis/courseType'
  import { getTeacherByPage } from '@/apis/teacher'
  import { getClassroomByPage } from '@/apis/classroom'
  import { getStudentByPage } from '@/apis/student'
  import ClassEditor from '@/components/Editor/ClassEditor'
  import ClassroomEditor from '@/components/Editor/ClassroomEditor'
  import TeacherEditor from '@/components/Editor/TeacherEditor'
  import StudentEditor from '@/components/Editor/StudentEditor'
  import CourseTypeSelector from '@/components/Selector/CourseTypeSelector'
  import TeacherFreeCalendar from './TeacherFreeCalendar'

  export default {
    components: {
      ClassEditor,
      ClassroomEditor,
      TeacherEditor,
      StudentEditor,
      CourseTypeSelector,
      TeacherFreeCalendar,
    },
    data() {
      return {
        formData: {
          id: null,
          courseTypeId: null,
          classId: null,
          classroomId: null,
          teacherId: null,
          courseDate: [],
          studentIds: [],
        },
        classList: [],
        courseTypeList: [],
        teacherList: [],
        classroomList: [],
        studentList: [],
        rules: {
          classId: [
            { required: true, trigger: 'change', message: '请选择班级' },
          ],
          classroomId: [
            { required: true, trigger: 'change', message: '请选择教室' },
          ],
          courseTypeId: [
            { required: true, trigger: 'change', message: '请选择课程类型' },
          ],
          teacherId: [
            { required: true, trigger: 'change', message: '请选择教师' },
          ],
          startDate: [
            { required: true, trigger: 'change', message: '请选择开始日期' },
          ],
          studentIds: [
            { required: true, trigger: 'change', message: '请选择学生' },
          ],
        },
        title: '',
        dialogFormVisible: false,
      }
    },
    methods: {
      init() {
        this.getClassList()
        this.getClassroomList()
        this.getTeacherList()
        this.getStudentList()

        getCourseTypeByPage().then(({ list }) => {
          this.courseTypeList = list
        })
      },
      getClassList() {
        getClassByPage().then(({ list }) => {
          this.classList = list
        })
      },
      getClassroomList() {
        getClassroomByPage().then(({ list }) => {
          this.classroomList = list
        })
      },
      getTeacherList() {
        getTeacherByPage().then(({ list }) => {
          this.teacherList = list
        })
      },
      getStudentList() {
        getStudentByPage().then(({ list }) => {
          this.studentList = list
        })
      },
      showEdit(row) {
        if (!row) {
          this.title = '添加'
        } else {
          this.title = '编辑'

          const {
            id,
            classId,
            classroomId,
            courseTypeId,
            endDate,
            startDate,
            students,
            teacher,
          } = row

          this.formData = {
            id,
            courseTypeId,
            classId,
            classroomId,
            teacherId: teacher && '' + teacher.id,
            courseDate: [startDate, endDate],
            studentIds: students.map((d) => d.id),
          }
        }
        this.init()
        this.dialogFormVisible = true
      },
      handleOpenEditor(name) {
        this.$refs[name].showEdit()
      },
      handleOpenTeacherFreeCalendar() {
        this.$refs.teacherFreeCalendarRef.open()
      },
      close() {
        this.$refs['form'].resetFields()
        this.formData = {
          id: null,
          courseTypeId: null,
          classId: null,
          classroomId: null,
          teacherId: null,
          courseDate: [],
          studentIds: [],
        }
        this.dialogFormVisible = false
      },
      save() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            let actionFn

            const {
              id,
              classId,
              courseTypeId,
              classroomId,
              teacherId,
              courseDate,
              studentIds,
            } = this.formData
            const data = {
              id,
              classId,
              courseTypeId,
              classroomId,
              teacherId,
              startDate: format(new Date(courseDate[0]), 'yyyy-MM-dd HH:mm:ss'),
              endDate: format(new Date(courseDate[1]), 'yyyy-MM-dd HH:mm:ss'),
              studentIds,
            }

            if (this.formData.id) {
              actionFn = updateCourse
            } else {
              actionFn = createCourse
            }

            await actionFn(data)
            this.$baseMessage('操作成功', 'success')
            this.$emit('on-success')
            this.close()
          } else {
            return false
          }
        })
      },
    },
  }
</script>
